package cn.seaboot.admin.security.login;

import cn.seaboot.admin.logger.service.LoginLogService;
import cn.seaboot.admin.mvc.Result;
import cn.seaboot.admin.mvc.utils.IpUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败异常处理
 * <p>
 * 实际上永远不会走到这里，因为有全局异常拦截
 *
 * @author Mr.css
 * @version 2021-12-23 12:01
 */
@Configuration
public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Resource
    private LoginLogService loginLogService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        Result result;
        if (exception instanceof BadCredentialsException ||
                exception instanceof UsernameNotFoundException) {
            result = Result.failed("Incorrect account password!");
        } else if (exception instanceof LockedException) {
            result = Result.failed("Account is locked!");
        } else if (exception instanceof CredentialsExpiredException) {
            result = Result.failed("Incorrect account password!");
        } else if (exception instanceof DisabledException) {
            result = Result.failed("Account is locked!");
        } else {
            result = Result.failed("Unknown exceptions!");
        }

        try {
            // 记录一下登录失败日志
            String ip = IpUtils.getIpAddress(request);
            String agent = request.getHeader("user-agent");
            String account = request.getParameter(LoginFilter.USERNAME_FIELD);
            loginLogService.insert(LoginFilter.CHANNEL_NAME, null, account, null, ip, agent, LoginStatus.FAILED);
        } catch (Exception e) {
            logger.error("login log failed: ", e);
        }
        response.getWriter().write(result.toString());
    }
}